package org.example.rocketmq.delay;

import org.apache.rocketmq.client.exception.MQBrokerException;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.client.producer.SendStatus;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.remoting.exception.RemotingException;

import java.util.concurrent.TimeUnit;

/**
 * 延迟消息
 * 延迟时间是由rocketmq规定好的，不能自己指定 1-18个级别
 * messageDelayLevel = [1s 5s 30s 1m 2m 3m 4m 5m 6m 7m 8m 9m 10m 30m 1h 2h]
 */
public class Producer {
    public static void main(String[] args) throws InterruptedException, RemotingException, MQClientException, MQBrokerException {
        asyncSend();
    }

    public static DefaultMQProducer getProducer() {
        //1.创建生产者producer，并指定组名
        DefaultMQProducer producer = new DefaultMQProducer("producer-group1");
        //2.指定nameserver
        producer.setNamesrvAddr("192.168.3.109:9876;192.168.3.108:9876");
        return producer;
    }

    /**
     * 发送延时消息
     */
    public static void asyncSend() throws MQClientException, RemotingException, InterruptedException, MQBrokerException {
        //1.创建生产者producer，并指定组名
        DefaultMQProducer producer = getProducer();
        //3.启动producer
        producer.start();

        for (int i = 0; i < 10; i++) {
            //4.创建消息对象，指定topic tag 消息体
            /**
             * 参数
             *  1. topic
             *  2. tag
             *  3. content消息体
             */
            Message message = new Message("delayTopic", "tag1", ("hello world " + i).getBytes());

            //5.设置延时级别
            message.setDelayTimeLevel(2);

            //6.发送消息
            SendResult result = producer.send(message, 1000);
            //发送状态
            SendStatus status = result.getSendStatus();
            //消息ID
            String msgId = result.getMsgId();
            //接收消息的队列ID
            int queueId = result.getMessageQueue().getQueueId();

            System.out.println("result ==> status:" + status + " msgId:" + msgId + " queueId:" + queueId);
            //休眠1s
            TimeUnit.SECONDS.sleep(1);
        }

        //6.关闭生产者
        producer.shutdown();
    }
}
